package com.example.controller;

import ch.qos.logback.core.util.FileUtil;
import com.example.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/files")
public class FileController {


    private static final String Path="C:\\Users\\zhouyingying\\Desktop\\wly毕设\\文件处\\photo\\";
    private static final String Path2="C:\\Users\\zhouyingying\\Desktop\\高校勤工助学系统\\文件处\\文件2\\";


//    @Value("${seatPhoto.path}")
//    private String Path;

    // 图片文件上传
    @PostMapping("/uploadFile")
    public R save(MultipartFile file){

        //原始文件名称
        String originalFilename = file.getOriginalFilename();  //abc.jpg    abcd.png
        System.out.println("原始文件名称:"+originalFilename);
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));  //截取文件名后面的后缀  .jpg/.png


        //随机生成5位数
        Integer num = (int) ((Math.random() * 9 + 1) * 1000000);
        String filename = String.valueOf(num)+substring;
//        String filename = num.toString()+substring;

        //创建一个目录对象
        File dir =new File(Path);
        //判断当前目录 Path 是否存在
        if (!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
        //file是一个临时文件，需要将转存到指定位置下，否则本次请求完成后临时文件会删除
            file.transferTo(new File(Path+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success("上传成功",filename);
    }

    // 文件上传
    @PostMapping("/uploadFile2")
    public R save2(MultipartFile file){


        //原始文件名称
        String originalFilename = file.getOriginalFilename();  //abc.jpg    abcd.png
        System.out.println("原始文件名称2:"+originalFilename);
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));  //截取文件名后面的后缀  .jpg/.png

        //随机生成5位数
        Integer num = (int) ((Math.random() * 9 + 1) * 10000);
        String filename = String.valueOf(num)+originalFilename;

        //创建一个目录对象
        File dir =new File(Path2);
        //判断当前目录 Path2 是否存在
        if (!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
            //file是一个临时文件，需要将转存到指定位置下，否则本次请求完成后临时文件会删除
            file.transferTo(new File(Path2+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success("上传成功",filename);

    }

    @GetMapping("/downloadFile")
    public void download(String name, HttpServletResponse response){

        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(Path + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/downloadFile2")
    public void downloadDevtool(String name, HttpServletResponse response) throws IOException {

        File file = new File(name);
        String filename = name.substring(name.lastIndexOf("/")+1);
        response.setContentType("application/x-download");
//        response.setHeader("content-Disposition", "attachment;filename=" + filename);  //这个下载 下载之后的中文变成下划线等乱码

        //设置成浏览器能看懂的编码格式
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO8859-1"));
        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream(new File(Path2 + name));
            int len = 0;
            byte buffer[] = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = fileInputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }



}
